package li.com.springaidemo.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.netty.util.internal.StringUtil;
import jakarta.annotation.PostConstruct;
import jakarta.websocket.server.PathParam;
import li.com.springaidemo.common.R;
import li.com.springaidemo.mapper.CronMapper;
import li.com.springaidemo.pojo.Cron;
import li.com.springaidemo.service.CronService;
import li.com.springaidemo.timing.AddSchedule;
import li.com.springaidemo.timing.SchedulerUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.service.annotation.PostExchange;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/cron")
public class CronController {

    @Autowired
    private AddSchedule addSchedule;
    @Autowired
    private CronService cronService;
    @Autowired
    private CronMapper cronMapper;
    @GetMapping("/init")
    public R init(){
        Cron cron = cronService.getOne(new QueryWrapper<Cron>().eq("id", 0));
        return R.success(cron.getState());
    }
    @GetMapping("/openAllCron")
    public R openAllCron(){
        addSchedule.putHiredTask();
        cronService.updateById(new Cron(0,"0","0","0","1"));
        return R.success();
    }
    @GetMapping("/page")
    public R getTame(@PathParam("input") String input){
        QueryWrapper<Cron> queryWrapper = new QueryWrapper<Cron>().ne("id", "0");
        if (!StringUtil.isNullOrEmpty(input)&&!input.equals("0")) {
            queryWrapper.like("name", input);
        }
        List<Cron> list = cronService.list(queryWrapper);
        return R.success(list);
    }

    @GetMapping("/open")
    public R updateTame(@PathParam("id") Integer id){
        cronMapper.openState(id);
        List<Integer> idList = new ArrayList<>();
        idList.add(id);
        SchedulerUtil.delete(idList);
        addSchedule.addHiredTask(idList);
        return R.success();
    }
    @GetMapping("/close")
    public R closeTame(@PathParam("id") Integer id){
        cronMapper.closeState(id);
        List<Integer> idList = new ArrayList<>();
        idList.add(id);
        SchedulerUtil.delete(idList);
        return R.success();
    }
    @PostMapping("/del")
    public R delTame(@RequestBody Cron cron){
        cronMapper.deleteById(cron);
        List<Integer> idList = new ArrayList<>();
        idList.add(cron.getId());
        SchedulerUtil.delete(idList);
        return R.success();
    }

    @PostMapping("/addOrUpdate")
    public R addOrUpdateTame(@RequestBody Cron cron){
        if(cron.getId()!=null){
            cronMapper.updateById(cron);
        }else {
            cronService.save(cron);
            addSchedule.addHiredTask(Collections.singletonList(cron.getId()));
        }
        return R.success();
    }

}
